package com.yb0os1.controller.user;

import com.yb0os1.constant.StatusConstant;
import com.yb0os1.entity.Dish;
import com.yb0os1.result.Result;
import com.yb0os1.serve.DishServe;
import com.yb0os1.vo.DishVO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishServe dishServe;
    @Autowired
    private RedisTemplate redisTemplate;
    @Operation(summary = "根据分类ID查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> getDishByCategoryId(Long categoryId){
        // 构造redis的key  dish_categoryId
        String key = "dish_" + categoryId;
        //查询redis中是否含有菜品数据
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (list!=null && !list.isEmpty()){
            //非空 无需查询数据库
            return Result.success(list);
        }
        //不存在 查询数据库
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        list = dishServe.listWithFlavor(dish);
        //放到redis
        redisTemplate.opsForValue().set(key,list);
        return Result.success(list);
    }
}
